from datetime import datetime
from app import db
from sqlalchemy.orm import joinedload

# 订单主表模型
class Order(db.Model):
    __tablename__ = 'tb_order'
    
    order_id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='订单ID(主键)')
    user_id = db.Column(db.BigInteger, db.ForeignKey('tb_user.user_id', ondelete='SET NULL'), comment='用户ID')
    market_id = db.Column(db.BigInteger, db.ForeignKey('tb_supermarket.market_id'), comment='超市ID')
    order_no = db.Column(db.String(50), nullable=False, unique=True, comment='订单编号')
    total_amount = db.Column(db.Numeric(10, 2), default=0.00, comment='订单总金额')
    pay_amount = db.Column(db.Numeric(10, 2), default=0.00, comment='实付金额')
    discount_amount = db.Column(db.Numeric(10, 2), default=0.00, comment='优惠金额')
    status = db.Column(db.Integer, default=0, comment='订单状态(0-待支付,1-已支付,2-已发货,3-已完成,4-已取消)')
    pay_type = db.Column(db.Integer, comment='支付方式(1-微信,2-支付宝,3-积分)')
    pay_time = db.Column(db.DateTime, comment='支付时间')
    address_id = db.Column(db.BigInteger, comment='收货地址ID')
    remark = db.Column(db.String(255), comment='订单备注')
    create_time = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    # 定义关联关系 - 使用back_populates
    user = db.relationship('User', back_populates='orders')
    supermarket = db.relationship('Supermarket', back_populates='orders')
    items = db.relationship('OrderItem', back_populates='order', cascade='all, delete-orphan')
    
    def __repr__(self):
        return f'<Order {self.order_id}>'
    
    def to_dict(self):
        """转换为字典，用于API响应"""
        return {
            'order_id': self.order_id,
            'user_id': self.user_id,
            'market_id': self.market_id,
            'order_no': self.order_no,
            'total_amount': float(self.total_amount) if self.total_amount else 0.0,
            'pay_amount': float(self.pay_amount) if self.pay_amount else 0.0,
            'discount_amount': float(self.discount_amount) if self.discount_amount else 0.0,
            'status': self.status,
            'pay_type': self.pay_type,
            'pay_time': self.pay_time.strftime('%Y-%m-%d %H:%M:%S') if self.pay_time else None,
            'address_id': self.address_id,
            'remark': self.remark,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S') if self.create_time else None,
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S') if self.update_time else None,
            'items': [item.to_dict() for item in self.items]
        }


# 订单明细表模型
class OrderItem(db.Model):
    __tablename__ = 'tb_order_detail'
    
    detail_id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='详情ID(主键)')
    order_id = db.Column(db.BigInteger, db.ForeignKey('tb_order.order_id'), comment='订单ID')
    box_id = db.Column(db.BigInteger, db.ForeignKey('tb_blind_box.box_id'), comment='盲盒ID')
    quantity = db.Column(db.Integer, comment='购买数量')
    price = db.Column(db.Numeric(10, 2), comment='单价(元)')
    
    # 关联盲盒信息
    blind_box = db.relationship('BlindBox', lazy=True)
    order = db.relationship('Order', back_populates='items')
    
    def __repr__(self):
        return f'<OrderItem {self.detail_id}>'
    
    def to_dict(self):
        """转换为字典，用于API响应"""
        return {
            'detail_id': self.detail_id,
            'order_id': self.order_id,
            'box_id': self.box_id,
            'quantity': self.quantity,
            'price': float(self.price) if self.price else 0.0,
            'box_name': self.blind_box.name if self.blind_box else None
        } 